"""
    自己实现云通讯的短信接口
"""
import base64
import hashlib

import requests
import time


class SmsAPI:
    def __init__(self, accId, accToken, appId):
        self.accId = accId
        self.accToken = accToken
        self.appId = appId
        self.now = time.strftime("%Y%m%d%H%M%S")

    def get_url(self):
        """
        获取请求的URL地址：API文档
        sig:md5(账户ID+授权令牌+时间戳) 大写
        """
        s = self.accId + self.accToken + self.now
        m = hashlib.md5()
        m.update(s.encode())
        sig = m.hexdigest().upper()
        return f"https://app.cloopen.com:8883" \
               f"/2013-12-26/Accounts/{self.accId}" \
               f"/SMS/TemplateSMS?sig={sig}"

    def get_data(self, tid, mobile, datas):
        """
        获取请求体
        """
        return {
            "to": mobile,
            "appId": self.appId,
            "templateId": tid,
            "datas": datas,
        }

    def get_headers(self):
        """
        获取请求头
        """
        s = self.accId + ":" + self.now
        auth = base64.b64encode(s.encode()).decode()
        return {
            "Accept": "application/json",
            "Content-Type": "application/json;charset=utf-8",
            # "Content-Length": 256,
            "Authorization": auth,
        }

    def sendMessage(self, tid, mobile, datas):
        """
            发送短信接口方法
        """
        url = self.get_url()
        data = self.get_data(tid, mobile, datas)
        headers = self.get_headers()

        resp = requests.post(url=url,
                             json=data,
                             headers=headers)
        return resp


if __name__ == '__main__':
    accId = '2c94811c9860a9c40198d56a4cc7135a'
    accToken = '8aa6fe0910fd4f09a9b692957869bb57'
    appId = '2c94811c9860a9c40198d56a4e4e1361'
    sdk = SmsAPI(accId, accToken, appId)
    tid = '1'
    mobile = '18892689998'
    datas = ('1016', '5')
    resp = sdk.sendMessage(tid, mobile, datas)
    print(resp.__dict__)
